package cc.owoo.godpen.network.console;

import cc.owoo.godpen.structure.ByteList;
import cc.owoo.godpen.thread.WaitThread;
import cc.owoo.godpen.network.SocketUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 控制台服务
 * Created by nimensei
 * 2022-03-31 上午 01:58
 **/
public class ConsoleServer {
    private final ByteList pool = new ByteList();

    /**
     * 启动控制台服务器
     *
     * @param port 端口
     */
    public void launch(int port) {
        try {
            SocketUtil.server(port, socket -> {
                try {
                    link(socket);
                } catch (IOException ignored) {
                }
            }, () -> launch(port));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理客户端连接
     *
     * @param socket 客户端
     * @throws IOException 处理异常
     */
    private void link(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        try {
            int b;
            while ((b = inputStream.read()) != -1) {
                synchronized (pool) {
                    pool.write(b);
                }
                printThread.execute();
            }
        } catch (IOException ignored) {
        }
        synchronized (pool) {
            pool.write("\n".getBytes(StandardCharsets.UTF_8));
        }
        printThread.execute();
        socket.close();
    }

    /**
     * 输出线程
     */
    private final WaitThread printThread = new WaitThread(5) {
        @Override
        public void run() {
            synchronized (pool) {
                byte[] bytes = pool.toByteArray();
                String s = new String(bytes, StandardCharsets.UTF_8);
                System.out.print(s);
                pool.reset();
            }
        }
    };
}
